package com.greenantmall.adapter;

import java.text.DecimalFormat;
import java.util.List;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.greenantmall.AntHomeApplication;
import com.greenantmall.R;
import com.greenantmall.adapter.ShoppingCartListAdapter.ShoppingCartItemData;
import com.greenantmall.bean.Goods;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.bean.StoreInfo;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ShoppingCartDeleteListAdapter extends BaseAdapter
{
    private Activity mActivity;
    private List<ShoppingCartItemData> mDataList;
    private DecimalFormat mDecimalFormat;

    public ShoppingCartDeleteListAdapter(Activity activity, List<ShoppingCartItemData> dataList)
    {
        mActivity = activity;
        mDataList = dataList;
        mDecimalFormat = new DecimalFormat("#########.##");
    }

    public void release()
    {

    }
    
    @Override
    public int getCount()
    {
        int count = 0;
        if (mDataList != null)
        {
            count = mDataList.size();
        }
        return count;
    }

    @Override
    public Object getItem(int position)
    {
        int size = mDataList.size();
        if (position >= 0 && position < size - 1)
        {
            return mDataList.get(position);
        }

        return null;
    }

    @Override
    public long getItemId(int position)
    {
        return 0;
    }

    /**
	 * 0:普通商品行；1：商品休市提示行；2：店铺名称行；3：商品下架提示行；
	 */
    @Override
	public int getItemViewType(int position) {
		return mDataList.get(position).itemType;
	}

	@Override
	public int getViewTypeCount() {
		return 4;
	}

	@Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        Log.d("CEXX", "CEXX ---> getView ---> position : " + position + " ---> type : " + getItemViewType(position));
        View child = convertView;
        int type = this.getItemViewType(position);
        if(type == 0) {
        	ViewHolder holder = null;
            if (child == null)
            {
                child = LayoutInflater.from(mActivity).inflate(R.layout.shopping_cart_listview_item, null);
                holder = new ViewHolder(child);
                child.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) child.getTag();
            }

            holder.setPosition(position);
            ShoppingCartItemData itemData = mDataList.get(position);
            if (itemData != null)
            {
                ShoppingCart usc = itemData.mUIShoppingCart;
                Goods goods = usc.getGoods();
                // CheckBox
                holder.getCheckBox().setEnabled(true);
            	holder.getCheckBox().setChecked(itemData.isChecked);
                // name
                String name = (goods==null ? "" : goods.getDescriptionAndSpecs());
                name = (name==null ? "" : name);
                holder.getTvName().setText(name);
                // price
                double price = (goods==null ? 0 : goods.getRealPrice());
                String unit = (goods==null ? "" : goods.getUnit());
                String yuan = mActivity.getResources().getString(R.string.shopping_cart_price_yuan);
                holder.getTvPrice().setText(mDecimalFormat.format(price) + yuan + " / " + unit);
                // count unit
                double stock = goods.getStock();
                double quantity = usc.getQuantity();
                if(quantity > stock) {
                	usc.put(ShoppingCart.ATTR_QUANTITY, stock);
                	quantity = usc.getQuantity();
                }
                String stepUnit = (goods==null ? "" : goods.getWeighUnit());
                holder.getTvCountUnit().setText(quantity + stepUnit);
                // price by weight
                boolean priceByWeight = (goods==null ? true : goods.isWeighAble());
                if(priceByWeight)
                {
                    holder.getTvPriceByWeight().setVisibility(View.VISIBLE);
                }
                else
                {
                    holder.getTvPriceByWeight().setVisibility(View.GONE);
                }
                // icon
                String iconUrl = (goods==null ? "" : goods.getImageUrl());
                if(!TextUtils.isEmpty(iconUrl)) {
                	ImageLoader.getInstance().displayImage(iconUrl, holder.getViewIcon(),AntHomeApplication.imageDisplayOptions);
                }
                // sold out icon
                if(itemData.isSoldOut && !itemData.isOffShelf) {
                	holder.getViewSoldOutIcon().setVisibility(View.VISIBLE);
                }
                else {
                	holder.getViewSoldOutIcon().setVisibility(View.GONE);
                }
            }
        }
        else if(type == 1) {
        	ViewHolder1 holder1 = null;
            if (child == null)
            {
                child = LayoutInflater.from(mActivity).inflate(R.layout.shopping_cart_listview_item_1, null);
                holder1 = new ViewHolder1(child);
                child.setTag(holder1);
            }
            else
            {
                holder1 = (ViewHolder1) child.getTag();
            }
            
            ShoppingCartItemData itemData = mDataList.get(position);
            if(itemData.notOpenType == 1) {
            	holder1.getTvStoreClosePrompt().setText(mActivity.getResources().getString(R.string.store_close_prompt_1));
            }
            else {
            	holder1.getTvStoreClosePrompt().setText(mActivity.getResources().getString(R.string.store_close_prompt_2));
            }
        }
        else if(type == 2) {
        	ViewHolder2 holder2 = null;
            if (child == null)
            {
                child = LayoutInflater.from(mActivity).inflate(R.layout.shopping_cart_listview_item_2, null);
                holder2 = new ViewHolder2(child);
                child.setTag(holder2);
            }
            else
            {
                holder2 = (ViewHolder2) child.getTag();
            }
            
            holder2.setPosition(position);
            ShoppingCartItemData itemData = mDataList.get(position);
            if(AntHomeApplication.storeInfos != null
            		&& AntHomeApplication.storeInfos.get(itemData.storeId) != null) {
            	StoreInfo storeInfo = AntHomeApplication.storeInfos.get(itemData.storeId);
            	// 店铺名称
            	String storeName = storeInfo.getDescrip();
            	storeName = (storeName==null ? "" : storeName);
            	holder2.getTvStoreName().setText(storeName);
            	// 运费提醒
            	String formatStr = mActivity.getResources().getString(R.string.shopping_cart_freight_prompt);
            	holder2.getTvFreightPrompt().setText(String.format(formatStr, mDecimalFormat.format(storeInfo.getStartcost())));
            	
            	CheckBox checkBox = holder2.getCheckBox();
            	checkBox.setOnCheckedChangeListener(null);
            	checkBox.setChecked(itemData.isChecked);
            	checkBox.setOnCheckedChangeListener(holder2);
            }
            else {
            	holder2.getTvStoreName().setText("");
            	holder2.getTvFreightPrompt().setText("");
            	
            	CheckBox checkBox = holder2.getCheckBox();
            	checkBox.setOnCheckedChangeListener(null);
            	checkBox.setChecked(itemData.isChecked);
            	checkBox.setOnCheckedChangeListener(holder2);
            }
        }
        else if(type == 3) {
        	ViewHolder3 holder3 = null;
            if (child == null)
            {
                child = LayoutInflater.from(mActivity).inflate(R.layout.shopping_cart_listview_item_3, null);
                holder3 = new ViewHolder3(child);
                child.setTag(holder3);
            }
            else
            {
                holder3 = (ViewHolder3) child.getTag();
            }
        }

        return child;
    }
	
	private class ViewHolder1 {
		private View mContentView;
		private TextView mTvStoreClosePrompt;
		
		public ViewHolder1(View contentView) {
			mContentView = contentView;
		}
		
		public TextView getTvStoreClosePrompt() {
			if(mTvStoreClosePrompt == null) {
				mTvStoreClosePrompt = (TextView)mContentView.findViewById(R.id.shopping_cart_item_name);
			}
			return mTvStoreClosePrompt;
		}
	}
	
	private class ViewHolder2 implements OnCheckedChangeListener {
		private View mContentView;
		private CheckBox mCheckBox;
		private TextView mTvStoreName;
		private TextView mTvFreightPrompt;
		
		private int mPosition;
        
		public ViewHolder2(View contentView) {
			mContentView = contentView;
			getCheckBox();
		}
		
		public void setPosition(int position)
        {
            this.mPosition = position;
        }

		public CheckBox getCheckBox() {
			if(mCheckBox == null) {
				mCheckBox = (CheckBox)mContentView.findViewById(R.id.shopping_cart_item_check);
				mCheckBox.setOnCheckedChangeListener(this);
			}
			return mCheckBox;
		}

		public TextView getTvStoreName() {
			if(mTvStoreName == null) {
				mTvStoreName = (TextView)mContentView.findViewById(R.id.shopping_cart_item_store_name);
			}
			return mTvStoreName;
		}

		public TextView getTvFreightPrompt() {
			if(mTvFreightPrompt == null) {
				mTvFreightPrompt = (TextView)mContentView.findViewById(R.id.shopping_cart_item_freight_prompt);
			}
			return mTvFreightPrompt;
		}

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			ShoppingCartItemData currentItemData = mDataList.get(mPosition);
			currentItemData.isChecked = isChecked;
			for(ShoppingCartItemData itemData : mDataList) {
				if(itemData.itemType != 0 || itemData.isOffShelf) {
    				continue;
    			}
				
				if(TextUtils.isEmpty(currentItemData.storeId)) {
					if(TextUtils.isEmpty(itemData.mUIShoppingCart.getStoreId())) {
						itemData.isChecked = isChecked;
					}
				}
				else if(currentItemData.storeId.equals(itemData.mUIShoppingCart.getStoreId())) {
					itemData.isChecked = isChecked;
				}
			}
			notifyDataSetChanged();
		}
	}
	
	private class ViewHolder3 {
		private View mContentView;
		private TextView mTvOffShelfPrompt;
		
		public ViewHolder3(View contentView) {
			mContentView = contentView;
		}
		
		public TextView TvStoreClosePrompt() {
			if(mTvOffShelfPrompt == null) {
				mTvOffShelfPrompt = (TextView)mContentView.findViewById(R.id.shopping_cart_item_name);
			}
			return mTvOffShelfPrompt;
		}
	}

    private class ViewHolder implements OnCheckedChangeListener
    {
        private View mContentView;

        private TextView mTvStoreName;
        private CheckBox mCheckBox;
        private ImageView mViewIcon;
        private View mViewSoldOutIcon;
        private TextView mTvName;
        private TextView mTvPrice;
        private TextView mTvCountUnit;
        private TextView mTvPriceByWeight;
        private Button mBtnSubtract;
        private Button mBtnAdd;
        private View mBtnContainer;
        
        private int mPosition;
        
        public ViewHolder(View contentView)
        {
            this.mContentView = contentView;
            getBtnSubtract();
            getBtnAdd();
            getCheckBox();
            getBtnContainer().setVisibility(View.INVISIBLE);
        }
        
        public void setPosition(int position)
        {
            this.mPosition = position;
        }

		public CheckBox getCheckBox()
        {
            if (mCheckBox == null)
            {
                mCheckBox = (CheckBox) mContentView.findViewById(R.id.shopping_cart_item_check);
                mCheckBox.setOnCheckedChangeListener(this);
            }
            return mCheckBox;
        }

        public ImageView getViewIcon()
        {
            if (mViewIcon == null)
            {
                mViewIcon = (ImageView)mContentView.findViewById(R.id.shopping_cart_item_icon);
            }
            return mViewIcon;
        }
        
        public View getViewSoldOutIcon()
        {
            if (mViewSoldOutIcon == null)
            {
            	mViewSoldOutIcon = mContentView.findViewById(R.id.shopping_cart_item_solo_out_icon);
            }
            return mViewSoldOutIcon;
        }

        public TextView getTvName()
        {
            if (mTvName == null)
            {
                mTvName = (TextView) mContentView.findViewById(R.id.shopping_cart_item_name);
            }
            return mTvName;
        }

        public TextView getTvPrice()
        {
            if (mTvPrice == null)
            {
                mTvPrice =
                    (TextView) mContentView.findViewById(R.id.shopping_cart_item_price);
            }
            return mTvPrice;
        }
        
        public TextView getTvPriceByWeight()
        {
            if (mTvPriceByWeight == null)
            {
                mTvPriceByWeight =
                    (TextView) mContentView.findViewById(R.id.shopping_cart_item_price_by_weight);
            }
            return mTvPriceByWeight;
        }
        
        public TextView getTvCountUnit()
        {
            if (mTvCountUnit == null)
            {
                mTvCountUnit =
                    (TextView) mContentView.findViewById(R.id.shopping_cart_item_count_unit);
            }
            return mTvCountUnit;
        }
        
        public View getBtnContainer() {
        	if(mBtnContainer == null) {
        		mBtnContainer = mContentView.findViewById(R.id.shopping_cart_item_price_and_count_ll);
        	}
			return mBtnContainer;
		}

		public Button getBtnSubtract()
        {
            if (mBtnSubtract == null)
            {
                mBtnSubtract = (Button) mContentView.findViewById(R.id.shopping_cart_item_subtract);
            }
            return mBtnSubtract;
        }
        
        public Button getBtnAdd()
        {
            if (mBtnAdd == null)
            {
                mBtnAdd = (Button) mContentView.findViewById(R.id.shopping_cart_item_add);
            }
            return mBtnSubtract;
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
        	// 是否全部选中
            mDataList.get(mPosition).isChecked = isChecked;
            
            // 统一店铺的商品是否全部选中
        	boolean isAllCheckedSameStore = true;
        	ShoppingCartItemData currentItemData = mDataList.get(mPosition);
        	String storeId = currentItemData.mUIShoppingCart.getStoreId();
        	if(TextUtils.isEmpty(storeId)) {
        		for (ShoppingCartItemData itemData : mDataList)
                {
                	if(itemData.itemType != 0 || itemData.isOffShelf) {
        				continue;
        			}
                	
                    if(TextUtils.isEmpty(itemData.mUIShoppingCart.getStoreId())) {
                    	if(!itemData.isChecked) {
                    		isAllCheckedSameStore = false;
                    		break;
                    	}
                    }
                }
        		
        		Log.d("CEXX", "CEXX => isAllCheckedSameStore 00 : " + isAllCheckedSameStore);
        		for (ShoppingCartItemData itemData : mDataList)
                {
                	if(itemData.itemType == 2 && TextUtils.isEmpty(itemData.storeId)) {
        				itemData.isChecked = isAllCheckedSameStore;
        				break;
        			}
                }
        	}
        	else {
        		for (ShoppingCartItemData itemData : mDataList)
                {
                	if(itemData.itemType != 0 || itemData.isOffShelf) {
        				continue;
        			}
                	
                    if(storeId.equals(itemData.mUIShoppingCart.getStoreId())) {
                    	if(!itemData.isChecked) {
                    		isAllCheckedSameStore = false;
                    		break;
                    	}
                    }
                }
        		
        		Log.d("CEXX", "CEXX => isAllCheckedSameStore 01 : " + isAllCheckedSameStore);
        		for (ShoppingCartItemData itemData : mDataList)
                {
                	if(itemData.itemType == 2 && storeId.equals(itemData.storeId)) {
        				itemData.isChecked = isAllCheckedSameStore;
        				break;
        			}
                }
        	}
        	notifyDataSetChanged();
        }
    }
}
